package com.sdonkey.score.controller;

import com.sdonkey.score.bean.*;
import com.sdonkey.score.dto.UserAccountVo;
import com.sdonkey.score.dto.UserExtractDto;
import com.sdonkey.score.dto.UserTowardBalanceDto;
import com.sdonkey.score.service.IAdScoreManagerService;
import com.sdonkey.score.service.IUserAccountService;
import com.sdonkey.score.service.IUserMsgService;
import com.sdonkey.score.util.FormValidateUtil;
import com.sdonkey.score.util.ScoreHelper;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 广告积分管理
 *
 * @author 赵超
 * @email 773134958@qq.com
 */
@Controller
@RequestMapping(value = "/adScore", method = RequestMethod.POST)
public class AdScoreManageController {

    private Logger logger = Logger.getLogger(AdScoreManageController.class);

    @Autowired
    IUserMsgService userMsgService;
    @Autowired
    IUserAccountService userAccountService;
    @Autowired
    IAdScoreManagerService adScoreManagerService;


//------------------------------账户余额------------------------------------

    /**
     * 查询用户积分(账户余额页面数据加载)
     *
     * @return 用户余额实体类
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxselectUserBalance")
    public UserBalanceBean selectUserBalance(HttpSession session) throws Exception {
        String id = session.getAttribute("id").toString();
        return adScoreManagerService.selectUserBalance(id);
    }

    /**
     * 提现记录
     * 按日期范围查询提现记录
     *
     * @param page      页码
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxExtractRecords")
    public Map<String, Object> extractRecords(HttpSession session, String page, String startTime, String endTime) throws Exception {
        String id = session.getAttribute("id").toString();
        if (FormValidateUtil.isEmpty(page)) {
            page = "1";
        }
        int pageNum = Integer.parseInt(page);
        return adScoreManagerService.extractRecordsByDate(id, startTime, endTime, pageNum);
    }

    /**
     * 加载提现记录详情数据
     * userExtract.getStatus() == 1  成功  否则失败
     *
     * @param id 提现记录id
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxselectExtractDetail")
    public UserExtractDto selectExtractDetail(String id) throws Exception {
        return adScoreManagerService.selectExtractDetail(id);
    }

    /**
     * 给提现记录添加备注
     *
     * @param id   ==>	t_user_extract表的主键
     * @param note 提现备注
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxAddNote")
    public String addNote(String id, String note) throws Exception {
        int flag = adScoreManagerService.addNote(id, note);
        if (flag > 0) {
            return "1";
        }
        return "-1";                                                                    //  1  -1  添加备注成功与否
    }

    /**
     * 加载转入银行卡页面所需数据  用户账户（持有的银行卡）详情
     *
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxSelectUserBankCards")
    public List<UserAccountVo> selectUserBankCards(HttpSession session) throws Exception {
        String id = session.getAttribute("id").toString();
        return userAccountService.queryBankCardsById(id);
    }

    /**
     * 支付密码正确之后   确认提现或转入银行卡
     *
     * @param outBalance  提现金额
     * @param serviceCost 服务费
     * @param accountId   账户Id  对应一张银行卡
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxTransOutToBankCardExecute")
    public int transOutToBankCardExecute(HttpSession session, String outBalance, String serviceCost, String accountId) throws Exception {
        String userId = session.getAttribute("id").toString();
        return adScoreManagerService.transOutToBankCardExecute(userId, outBalance, serviceCost, accountId);
    }

    /**
     * 银行审核
     *
     * @param userId      用户id
     * @param outBalance  提现金额
     * @param serviceCost 服务费
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxBankControl")
    public int ajaxBankControl(String userId, String outBalance, String serviceCost) throws Exception {
        int i = 0;  //审核方法
        // TODO: 2017/1/16 0016  i等于审核方法的返回值
        if (i > 0) {
            userMsgService.sendMsgForAccountDefray(Integer.valueOf(userId), Double.valueOf(outBalance) + Double.valueOf(serviceCost), ScoreHelper.getDealType(ScoreHelper.transferToBank));
        }
        return i;
    }

    /**
     * 提现失败退还积分
     *
     * @param userId      用户id
     * @param outBalance  需退还积分
     * @param serviceCost 需退还服务费
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxTransferToBankFailed")
    public int ajaxTransferToBankFailed(String userId, String outBalance, String serviceCost) throws Exception {
        int i = adScoreManagerService.transferToBankFailed(userId, outBalance, serviceCost);
        if (i > 0) {
            userMsgService.sendMsgForAccountIncome(Integer.valueOf(userId), Double.valueOf(outBalance) + Double.valueOf(serviceCost), ScoreHelper.getDealType(ScoreHelper.transferToBankFailed));
            i = 1;
        }
        return i;
    }

    /**
     * 我的专项积分
     *
     * @param page 页码
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxMyScore")
    public Map<String, Object> myScore(HttpSession session, String page) throws Exception {
        String userid = session.getAttribute("id").toString();
        if (FormValidateUtil.isEmpty(page)) {
            page = "1";
        }
        int pageNum = Integer.parseInt(page);
        return adScoreManagerService.selectMyScore(userid, pageNum);
    }

    /**
     * 专项积分产品购买页面
     * 数据加载  内容商的产品（应用）
     *
     * @param developerId 内容商id
     * @param page        页码
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxselectProductions")
    public Map<String, Object> selectProductions(String developerId, String page) throws Exception {
        if (FormValidateUtil.isEmpty(page)) {
            page = "1";
        }
        int pageNum = Integer.parseInt(page);
        return adScoreManagerService.selectProductions(developerId, pageNum);
    }

    /**
     * 单个应用的详细信息
     *
     * @param applicationId 应用id
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxselectProductionDetail")
    public UserTowardBalanceDto selectProductionDetail(String applicationId) throws Exception {
        return adScoreManagerService.selectproductionDetail(applicationId);
    }

    /**
     * 应用的详细信息
     *
     * @param aId 应用id
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxSelectAppDetailByAid")
    public ApplicationNewBean ajaxSelectAppDetailByAid(String aId) throws Exception {
        return adScoreManagerService.selectAppInfoByAid(aId);
    }

    /**
     * 用户购买产品
     *
     * @param applicationId 应用id
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxBuyProduction")
    public String buyProduction(HttpSession session, String applicationId) throws Exception {
        String id = session.getAttribute("id").toString();
        Double price = adScoreManagerService.selectPriceByAppId(applicationId);
        int flag = adScoreManagerService.buyProduction(id, applicationId, price);
        if (flag > 0) {
            userMsgService.sendMsgForAccountDefray(Integer.valueOf(id), price, ScoreHelper.getDealType(ScoreHelper.payForApp));
            return "1";
        } else {
            return "-1";                                                                //1 -1 				购买成功失败
        }
    }

//------------------------------转账支付------------------------------------

    /**
     * 加载向内容商支付所需数据,加载用户可用的专项积分，用于验证输入金额是否大于可用金额
     *
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxtransferToDeveloper")
    public String transferToDeveloper(HttpSession session) throws Exception {
        String id = session.getAttribute("id").toString();
        String balance = adScoreManagerService.select_TowardBalance(id);
        if (balance == null || balance == "") {
            balance = "0.0";
        }
        return balance;
    }

    /**
     * 加载指定内容商的应用列表
     *
     * @param developerId 内容商ID
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxLoadDevApp")
    public List<ApplicationNewBean> ajaxLoadDevApp(String developerId) throws Exception {
        return adScoreManagerService.loadDevApp(developerId);
    }

    /**
     * 验证支付密码成功后  确认向内容商支付
     *
     * @param developerId 内容商id
     * @param outBalance  支付金额
     * @param note        备注
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxtransferToDeveloperExecute")
    public String transferToDeveloperExecute(HttpSession session, String developerId, String outBalance, String note) throws Exception {
        String userId = session.getAttribute("id").toString();
        int flag = adScoreManagerService.payToDeveloperExecute(userId, developerId, outBalance, note);
        if (flag > 0) {
            userMsgService.sendMsgForAccountDefray(Integer.valueOf(userId), Double.valueOf(outBalance), ScoreHelper.getDealType(ScoreHelper.payForApp));
            session.setAttribute("toId", developerId);
            session.setAttribute("outBalance", outBalance);
            return "1";
        } else {
            return "-1";                                                                 // 1 -1  支付成功失败
        }
    }

    /**
     * 加载向内容商转账界面所需已关注内容商
     *
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxGetDevList_Ad")
    public List<DeveloperBean> getDevList_Ad(HttpSession session) throws Exception {
        String userId = session.getAttribute("id").toString();
        return adScoreManagerService.devListByID(userId);
    }

    /**
     * 加载向好友转账界面所需好友列表
     *
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxgetFriendList_Ad")
    public List<FriendBean> getFriendList_Ad(HttpSession session) throws Exception {
        String userId = session.getAttribute("id").toString();
        Map<String, Object> map = adScoreManagerService.friendListByID(userId);
        List<FriendBean> friendsList = (List<FriendBean>) map.get("friendsList");
        return friendsList;
    }

    /**
     * 支付密码校验成功之后  向好友支付
     *
     * @param friendId   好友id
     * @param outBalance 转账金额
     * @param note
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxtransferToFriendExecute")
    public String transferToFriendExecute(HttpSession session, String friendId, String outBalance, String note) throws Exception {
        String userId = session.getAttribute("id").toString();
        int flag = adScoreManagerService.payToFriendExecute(userId, friendId, outBalance, note);
        if (flag > 0) {
            userMsgService.sendMsgForAccountDefray(Integer.valueOf(userId), Double.valueOf(outBalance), ScoreHelper.getDealType(ScoreHelper.transferToFriend));
            userMsgService.sendMsgForAccountIncome(Integer.valueOf(friendId), Double.valueOf(outBalance), ScoreHelper.getDealType(ScoreHelper.transferToFriend));
            session.setAttribute("toId", friendId);
            session.setAttribute("outBalance", outBalance);
            return "1";
        } else {
            return "-1";                                                                // 1 -1 向好友支付  成功  失败
        }
    }

    /**
     * 为转账成功页面加载数据
     *
     * @param session
     * @param flag    flag = 'f'(向好友支付)  'c'/'d'(向内容商支付)   'a'(向应用支付，应用购买)
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxTransferToSomeOneSucceed")
    public Map<String, String> ajaxTransferToSomeOneSucceed(HttpSession session, String flag) throws Exception {
        String id = (String) session.getAttribute("toId");
        String balance = (String) session.getAttribute("outBalance");
        Map<String, String> map = new HashMap<>();
        String name = "";
        String donkeyNum = "";
        if ("c".equals(flag) || "d".equals(flag)) {
            DeveloperBean dev = adScoreManagerService.selectDevInfoById(id);
            donkeyNum = dev.getDonkey_num();
            name = dev.getCompany_name();
        } else if ("f".equals(flag)) {
            FriendBean friend = adScoreManagerService.selectFriendInfoById(id);
            donkeyNum = id;
            name = friend.getName();
        } else if ("a".equals(flag)) {
            ApplicationNewBean app = adScoreManagerService.selectAppInfoByAid(id);
            donkeyNum = id;
            name = app.getName();
        }
        map.put("toName", name);              //接收者用户名（公司名）
        map.put("toDonkeyNum", donkeyNum);    //接收者毛驴号
        map.put("toBalance", balance);        //转账金额
        return map;
    }

    /**
     * 转账记录数据加载
     *
     * @param session
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxselectTransferRecords")
    public List<TransferRecordBean> selectTransferRecords(HttpSession session) throws Exception {
        String userId = session.getAttribute("id").toString();
        return adScoreManagerService.selectTransferRecords(userId);
    }

    /**
     * 查找应用列表
     *
     * @param session
     * @param condition
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxSearchAppByCondition")
    public List<ApplicationNewBean> ajaxSearchAppByCondition(HttpSession session, String condition) throws Exception {
        String userId = session.getAttribute("id").toString();
        return adScoreManagerService.searchAppByCondition(userId, condition);
    }

    /**
     * 获取专项积分
     *
     * @param session
     * @param appId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxGetTowardBalanceByAppId")
    public Double ajaxGetTowardBalanceByAppId(HttpSession session, String appId) throws Exception {
        String userId = session.getAttribute("id").toString();
        return adScoreManagerService.getTowardBalanceByAppId(userId, appId);
    }

    /**
     * 向应用支付  未完成方法
     *
     * @param session
     * @param appId
     * @param outBalance
     * @param note
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxTransferToAppExecute")
    public String ajaxTransferToAppExecute(HttpSession session, String appId, String outBalance, String note) throws Exception {
        String userId = session.getAttribute("id").toString();
        int flag = adScoreManagerService.payToAppExecute(userId, appId, outBalance, note);
        if (flag > 0) {
            userMsgService.sendMsgForAccountDefray(Integer.valueOf(userId), Double.valueOf(outBalance), ScoreHelper.getDealType(ScoreHelper.payForApp));
            session.setAttribute("toId", appId);
            session.setAttribute("outBalance", outBalance);
            return "1";
        } else {
            return "-1";                                                                // 1 -1 向App支付  成功  失败
        }
    }

//----------------------------积分交易明细----------------------------------

    /**
     * 积分交易明细
     *
     * @param page         页码
     * @param paymentType  支出（收支）类型			1 收入 -1 支出
     * @param transferType 交易类型（0:合约广告 1:好友转账  3:应用支付 4:专项广告）（2:应用购买-已弃用此类型）
     * @param startTime    开始时间
     * @param endTime      结束时间
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/ajaxscoreDetail")
    public Map<String, Object> scoreDetail(HttpSession session, String page, String paymentType, String transferType, String startTime, String endTime) throws Exception {
        String userId = session.getAttribute("id").toString();
        //默认显示所有记录
        if (FormValidateUtil.isEmpty(page)) {
            page = "1";
        }
        int pageNum = Integer.parseInt(page);
        return adScoreManagerService.selectScoreDetails(userId, pageNum, paymentType, transferType, startTime, endTime);
    }

}
